package com.sky.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        //使用spring核心包进行加密
        String passwordAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        //System.out.println("com.sky.service.impl 33 passwordAsHex = " + passwordAsHex);

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!passwordAsHex.equals(employee.getPassword())) {

            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     * */
    @Override
    public EmployeeDTO addEmployee(EmployeeDTO employeeDTO) {
        String newUsername = employeeDTO.getUsername();
        Employee byUsername = employeeMapper.getByUsername(newUsername);
        //账号校验
        if (byUsername!=null){
            //已经存在该用户名
            throw new AccountLockedException(MessageConstant.ACCOUNT_REPEAT);
        }

//        Claims claims = JwtUtil.parseJWT(adminSecretKey, token);
//        Integer createUserId = (Integer) claims.get(JwtClaimsConstant.EMP_ID);
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);
        //默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //账号状态
        employee.setStatus(StatusConstant.ENABLE);
        //创建时间
        employee.setCreateTime(LocalDateTime.now());
        //更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //创建人
        //employee.setCreateUser(createUserId.longValue());
        //更新人
        //employee.setCreateUser(createUserId.longValue());
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        int i = employeeMapper.addEmployee(employee);
        if (i!=1){
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }
        return employeeDTO;
    }

    /**
     * 根据id查询员工
     * */
    @Override
    public Employee selectEmployeeById(Long id) {
        Employee employee = employeeMapper.selectEmployeeById(id);
        return employee;
    }

    /**
     * 分页查询
     * */
    @Override
    public PageResult employeePageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        List<Employee> employeeList = employeeMapper.findAllEmployee(employeePageQueryDTO.getName());
        PageInfo<Employee> employeePageInfo = new PageInfo<>(employeeList);
        //获取总页码数
        long total = employeePageInfo.getTotal();
        PageResult pageResult = new PageResult();
        pageResult.setRecords(employeeList);
        pageResult.setTotal(total);
        return pageResult;
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     * */
    @Override
    public Result editPassword(PasswordEditDTO passwordEditDTO) {
        Employee employee = employeeMapper.checkOldPassword(passwordEditDTO.getEmpId(), DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()));
        if (employee == null){
            return Result.error("密码错误");
        }
        employeeMapper.updatePasswordById(passwordEditDTO.getEmpId(), DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        return Result.success("更新成功");
    }



    /**
     * 编辑员工信息
     * */
    @Override
    public Result editEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);
        //更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //更新人
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
        return Result.success();
    }

    /**
     * 启用、禁用员工账号
     * */
    @Override
    public void updateStatus(Integer status,Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }

}
